<template>
  <div class="container">
    <xy-table ref="table" :api="api" :columns="columns">
      <template #addItem>
        <el-button icon="el-icon-plus" @click="showAddDialog" size="mini"
          >添加</el-button
        >
      </template>

      <template #operationButton="{ scope }">
        <el-button type="text" size="mini" @click="showEditDialog(scope.row)">
          {{ $language.local("修改签约信息") }}
        </el-button>

        <el-button type="text" size="mini" @click="handleDelete(scope.row)">
          {{ $language.local("删除") }}
        </el-button>
        <el-button
          type="text"
          :class="scope.row.FileCount > 0 ? 'success' : 'red'"
          size="mini"
          @click="manageAgreement(scope.row)"
        >
          {{ $language.local("协议管理") }}
        </el-button>
      </template>
    </xy-table>
    <el-dialog
      :title="$language.local('添加')"
      :visible.sync="addDialogVisible"
      :close-on-click-modal="false"
      :destroy-on-close="true"
      width="62%"
    >
      <el-form
        ref="addFormRef"
        :model="addForm"
        :rules="$rules"
        label-width="120px"
        status-icon
        class="grid-flex"
      >
        <el-form-item :label="$language.local('MerchantName')" prop="MID">
          <select-merchantid v-model="addForm.MID"></select-merchantid>
        </el-form-item>
        <el-form-item :label="$language.local('ServiceName')" prop="ServiceId">
          <select-service v-model="addForm.ServiceId"></select-service>
        </el-form-item>
        <el-form-item prop="BeginDate" :label="$language.local('开始日期')">
          <select-date v-model="addForm.BeginDate"></select-date>
        </el-form-item>
        <el-form-item
          prop="EndDate"
          :label="$language.local('EndDate')"
          :rules="EndDateRule"
        >
          <select-date v-model="addForm.EndDate"></select-date>
        </el-form-item>
        <el-form-item
          :label="$language.local('服务科目')"
          prop="ServiceContents"
        >
          <select-content
            v-model="addForm.ServiceContents"
            :serviceId="addForm.ServiceId"
          ></select-content>
        </el-form-item>
        <el-form-item :label="$language.local('ruleType')" prop="ruleType">
          <el-select v-model="addForm.ruleType" placeholder="请选择">
            <el-option
              v-for="item in ruleTypes"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$language.local('Rate')" prop="Rate">
          <xy-rate v-model="addForm.Rate"></xy-rate>
        </el-form-item>
        <el-form-item :label="$language.local('QZDRate')" prop="Rate">
          <xy-rate v-model="addForm.QZDRate"></xy-rate>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">{{
          $language.local("取消")
        }}</el-button>
        <el-button type="primary" @click="addSign('addFormRef')">{{
          $language.local("确定")
        }}</el-button>
      </span>
    </el-dialog>
    <el-dialog
      :title="$language.local('修改')"
      :visible.sync="editDialogVisible"
      width="70%"
      :close-on-click-modal="false"
      :destroy-on-close="true"
    >
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="$rules"
        label-width="140px"
        status-icon
        class="grid-flex"
      >
        <el-form-item :label="$language.local('MerchantName')" prop="MID">
          <select-merchantid v-model="editForm.MID"></select-merchantid>
        </el-form-item>
        <el-form-item :label="$language.local('ServiceName')" prop="ServiceId">
          <select-service v-model="editForm.ServiceId"></select-service>
        </el-form-item>
        <el-form-item prop="BeginDate" :label="$language.local('开始日期')">
          <select-date v-model="editForm.BeginDate"></select-date>
        </el-form-item>
        <el-form-item
          prop="EndDate"
          :label="$language.local('EndDate')"
          :rules="editEndDateRule"
        >
          <select-date v-model="editForm.EndDate"></select-date>
        </el-form-item>

        <el-form-item :label="$language.local('Rate')" prop="Rate">
          <xy-rate v-model="editForm.Rate"></xy-rate>
        </el-form-item>
        <el-form-item :label="$language.local('QZDRate')" prop="Rate">
          <xy-rate v-model="editForm.QZDRate"></xy-rate>
        </el-form-item>
        <el-form-item
          :label="$language.local('服务科目')"
          prop="ServiceContents"
          class="textarea"
        >
          <select-content
            :serviceId="editForm.ServiceId"
            v-model="editForm.ServiceContents"
          ></select-content>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">{{
          $language.local("取消")
        }}</el-button>
        <el-button type="primary" @click="editSign('editFormRef')">{{
          $language.local("确定")
        }}</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import API from "../../plugins/api";

export default {
  inject: ["reload"],

  data() {
    const validateEndTime = (rule, value, callback) => {
      if (!this.addForm.BeginDate) {
        callback(new Error("请输入开始时间！"));
        return;
      }
      const begTime = new Date(this.addForm.BeginDate);
      const endTime = new Date(value);
      if (endTime.compare(begTime)) {
        callback();
      } else {
        callback(new Error("请输入大于开始时间的日期！"));
      }
    };
    const validateEditEndTime = (rule, value, callback) => {
      console.log(this.editForm);
      if (!this.editForm.BeginDate) {
        callback(new Error("请输入开始时间！"));
        return;
      }
      const begTime = new Date(this.editForm.BeginDate);
      const endTime = new Date(value);
      if (endTime.compare(begTime)) {
        callback();
      } else {
        callback(new Error("请输入大于开始时间的日期！"));
      }
    };
    return {
      apiName: "/api/MerchantSign",
      api: new API("/api/MerchantSign/"),

      columns: {
        MerchantName: "淮北通财网络服务有限公司",
        ServiceName: "湖南好捷科技有限公司",

        BeginDate: "2021-03-08T00:00:00",
        EndDate: "2022-03-08T00:00:00",
        // ServiceContent: "",
        //  Rate: 6,
        // QZDRate: 7,
        //  Indate: "2021-03-08T13:39:00",
        FileCount: null,
        UseStatus: 1,
      },
      addDialogVisible: false,
      addForm: {
        MID: "",
        ServiceId: "",
        ServiceContents: [],
        ServiceContentId: "",
        ServiceContent: "",
        BeginDate: "",
        EndDate: "",
        Rate: 0,
        QZDRate: 0,
        Indate: "",
        UseStatus: 1,
      },
      editForm: {
        MID: "",
        ServiceId: "",
        ServiceContents: [],
        ServiceContentId: "",
        ServiceContent: "",
        BeginDate: "",
        EndDate: "",
        Rate: 0,
        QZDRate: 0,
        Indate: "",
        UseStatus: 1,
      },
      ruleTypes: [
        {
          label: "充值金额 * 签约费率",
          value: "A",
        },
        {
          label: "充值金额 - 充值金额/(1+签约费率)",
          value: "B",
        },
      ],
      editDialogVisible: false,
      EndDateRule: [
        { required: true, message: "不能为空", trigger: "blur" },
        { validator: validateEndTime, trigger: "blur" },
      ],
      editEndDateRule: [
        { required: true, message: "不能为空", trigger: "blur" },
        { validator: validateEditEndTime, trigger: "blur" },
      ],
    };
  },
  created() {
    let test = "12345";
    test = test.substr(-1);
    console.log(test);
  },
  methods: {
    showAddDialog() {
      this.addDialogVisible = true;
      this.getInvoiceType();
    },
    showEditDialog(row) {
      console.log(row);
      this.editDialogVisible = true;
      // let jsondata = JSON.stringify(row);
      // this.addForm = JSON.parse(jsondata);
      this.editForm = row;
      if (this.editForm.ServiceContent) {
        this.editForm.ServiceContent = this.editForm.ServiceContent.slice(
          0,
          -1
        );
        this.editForm.ServiceContents = this.editForm.ServiceContent.split("#");
      }

      // console.log(this.editForm.ServiceContent);
      // console.log(this.editForm.ServiceContents);
      // this.getInvoiceType();
    },
    addSign(formName) {
      console.log(formName);
      this.$refs[formName].validate(async (valided) => {
        if (!valided) {
          return;
        }
        this.addForm.ServiceContent = "";
        let arr = this.addForm.ServiceContents;
        for (let i = 0; i < arr.length; i++) {
          let element = arr[i];
          let index = element.indexOf("#");
          if (index != -1) {
            this.addForm.ServiceContentId += element.substr(0, index + 1);
            this.addForm.ServiceContent += element.substr(index + 1) + "#";
          }
        }
        console.log(this.addForm);

        let response = await this.$http.post(
          "/api/MerchantSign/Create",
          this.addForm
        );
        console.log(response);
        this.addDialogVisible = false;
        this.reload();
      });
    },
    editSign(formName) {
      this.$refs[formName].validate(async (valided) => {
        if (!valided) {
          return;
        }
        this.editForm.ServiceContent = "";
        this.editForm.ServiceContentId = "";
        let arr = this.editForm.ServiceContents;
        for (let i = 0; i < arr.length; i++) {
          let element = arr[i];
          let index = element.indexOf("#");
          if (index != -1) {
            this.editForm.ServiceContentId += element.substr(0, index + 1);
            this.editForm.ServiceContent += element.substr(index + 1) + "#";
          }
        }
        console.log(this.editForm);

        await this.$http.post("/api/MerchantSign/Edit", this.editForm);
        this.$message.success("修改成功");
        this.editDialogVisible = false;
        this.reload();
      });
    },
    manageAgreement(row) {
      console.log(row);
      this.$router.push({ path: "/merchant-contract", query: { id: row.Id } });
    },
    async handleDelete(row) {
      console.log(row);
      let res = await this.$confirm(
        `确定移除 ${row.MerchantName || ""}签约协议 吗？`
      );
      if (res == "confirm") {
        let response = await this.$http.delete(
          `/api/MerchantSign/Delete/${row.Id}`
        );
        console.log(response);
        if (response.data.Code == 200) {
          this.$message.success("删除成功");
          this.reload();
        }
      }
    },
    async getInvoiceType() {
      let response = await this.$http.get(
        "/api/Common/GetdictionaryItem?typenum=004"
      );
      console.log(response);
    },
  },
};
</script>

<style></style>
